package com.getway.filter;

import com.alibaba.fastjson.JSON;
import com.getway.entity.Anon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @create 2022-09-01
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private Anon anno;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request和response对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String path1 = request.getPath().toString();
        String[] split = path1.split("/");
        String path="";
        for(String s:split){

//            正则表达式判断是否为数字
            Pattern compile = Pattern.compile("[0-9]*");
            Matcher matcher = compile.matcher(s);
            if(!matcher.matches()){
                if(path.equals("")){
                    path="/"+s;
                }else {
                    path=path+"/"+s;
                }
            }
        }
        if(anno.getAnnoUrl().contains(path)){
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.hasText(token) && stringRedisTemplate.hasKey(token)){
            if (anno.getLoginUrl().contains(path)) {
                return chain.filter(exchange);
            }
            //判断当前登录者是否有相应的权限
            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
            String s = opsForValue.get(token);
            Map map = JSON.parseObject(s, Map.class);
            List<String> permission = (List<String>) map.get("permission");
            if (permission.contains(path)){
                return chain.filter(exchange);
            }else {
                return result(response,"权限不足",4001);
            }
        }else {
           return result(response,"请先登录",4000);
        }
    }
    public Mono<Void> result(ServerHttpResponse response,String msg,Integer code){
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //3.1设置状态吗
        Map<String,Object> map2 = new HashMap<>();
        map2.put("msg",msg);
        map2.put("code",code);
        byte[] bytes = JSON.toJSONString(map2).getBytes(StandardCharsets.UTF_8);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
